<script setup lang="ts">
import RoomMessage from "./components/RoomMessage.vue";
import RoomAction from "./components/RoomAction.vue";
import RoomStatus from "./components/RoomStatus.vue";
import { orderDetailApi } from "@/services/consult";
import { useRoute } from "vue-router";
import { onMounted, ref, onUnmounted, nextTick, provide } from "vue";
import type { ConsultOrderItem, Image } from "@/types/consult";
import io, { Socket } from "socket.io-client";
import { baseURL } from "@/utils/request";
import { useUserStore } from "@/stores";
import dayjs from "dayjs";
import { showToast } from "vant";
import type { Message, TimeMessages } from "@/types/room";
import { MsgType } from "@/enums";
import { OrderType } from "@/enums";
const store = useUserStore();
const route = useRoute();
const orderDetail = ref<ConsultOrderItem>();
async function getOrderDetail() {
  const res = await orderDetailApi(route.query.orderId as string);
  orderDetail.value = res.data;
}
provide("orderDetail", orderDetail);
const list = ref<Message[]>([]);
const loading = ref(false);
const time = ref(dayjs().format("YYYY-MM-DD HH:mm:ss"));
const initialMsg = ref(true);
let socket: Socket;
onMounted(() => {
  getOrderDetail();
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`,
    },
    query: {
      orderId: route.query.orderId,
    },
  });
  socket.on("connect", () => {
    console.log("连接成功");
  });
  socket.on("disconnect", () => {
    console.log("连接关闭");
  });
  socket.on("error", () => {
    console.log("发生错误");
  });

  // 获取聊天记录，如果是第一次（默认消息）
  socket.on("chatMsgList", ({ data }: { data: TimeMessages[] }) => {
    // data 数据 ===> [ {createTime}, ...items ]
    console.log(data);

    const arr: Message[] = [];
    data.forEach((item, i) => {
      // 记录每一段消息中最早的消息时间，获取聊天记录需要使用
      if (i === 0) time.value = item.createTime;
      arr.push({
        msgType: MsgType.Notify,
        msg: {
          content: item.createTime,
        },
        createTime: item.createTime,
        id: item.createTime,
      });
      arr.push(...item.items);
    });
    list.value.unshift(...arr);

    loading.value = false;
    if (!arr.length) return showToast("没有更多聊天记录了");

    if (initialMsg.value) {
      socket.emit("updateMsgStatus", arr[arr.length - 1].id);
      // 第一次需要滚动到最新的消息
      nextTick(() => {
        window.scrollTo(0, document.body.scrollHeight);
        initialMsg.value = false;
      });
    }
  });
  // 监听订单状态变化
  socket.on("statusChange", () => getOrderDetail());
  // 接收聊天消息
  socket.on("receiveChatMsg", async (event) => {
    console.log(event);
    // socket.emit("updateMsgStatus", event.id);
    list.value.push(event);
    await nextTick();
    window.scrollTo(0, document.body.scrollHeight);
  });
});
onUnmounted(() => {
  socket.close();
});
const onRefresh = () => {
  socket.emit("getChatMsgList", 20, time.value, orderDetail.value?.id);
};

// 发送文字信息
const onSendText = (text: string) => {
  socket.emit("sendChatMsg", {
    from: store.user?.id,
    to: orderDetail.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: text,
    },
  });
};

// 发送图片信息
const onSendImage = (image: Image) => {
  socket.emit("sendChatMsg", {
    from: store.user?.id,
    to: orderDetail.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: image,
    },
  });
};

const completeEva = (score: number) => {
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm);
  if (item) {
    item.msg.evaluateDoc = { score };
    item.msgType = MsgType.CardEva;
  }
};
provide("completeEva", completeEva);
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室"></cp-nav-bar>
    <div style="height: 52px">
      <RoomStatus
        :status="orderDetail?.status"
        :countdown="orderDetail?.countdown"
      ></RoomStatus>
    </div>
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <RoomMessage
        v-for="item in list"
        :key="item.id"
        :item="item"
      ></RoomMessage>
    </van-pull-refresh>
    <RoomAction
      @send-text="onSendText"
      @send-image="onSendImage"
      :disabled="orderDetail?.status !== OrderType.ConsultChat"
    ></RoomAction>
  </div>
</template>

<style lang="scss" scoped></style>
